import 'dart:async';

import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';

import '../../utils.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key key}) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  StreamSubscription subscription;
  @override
  void initState() {
    super.initState();
    subscription =
        Connectivity().onConnectivityChanged.listen(showConnectivityStackBar);
  }

  @override
  void dispose() {
    super.dispose();
    subscription.cancel();
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          title: Text("是否连接到网络？"),
        ),
        body: Center(
          child: ElevatedButton(
            child: Text(
              "检查连接",
              style: TextStyle(fontSize: 20),
            ),
            style: ElevatedButton.styleFrom(
              padding: EdgeInsets.all(12),
            ),
            onPressed: () async {
              final result = await Connectivity().checkConnectivity();
              showConnectivityStackBar(result);
            },
          ),
        ),
      );

  void showConnectivityStackBar(ConnectivityResult result) {
    final hasInternet = result != ConnectivityResult.none;
    final message = hasInternet ? '连接结果${result.toString()}' : '没有连接到Internet';
    final color = hasInternet ? Colors.green : Colors.red;
    Utils.showTopSnackBar(message, color);
  }
}
